package tau_sadna.tau_map;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import android.content.Context;
import android.util.Log;

public class FileIO {

	private static File filesDir;

	public static void initiate(Context c) {
		filesDir = c.getFilesDir();
	}


	public static int write(String fileContents, String fileName) {
		try {
			FileWriter out = new FileWriter(new File(filesDir,	fileName));
			out.write(fileContents);
			out.close();
			return 0;
		} catch (IOException e) {
			Log.e("IO_write", "io exception: "+e.toString());
			return 1;
		}
	}

	public static String read(String fileName) {
		StringBuilder stringBuilder = new StringBuilder();
		String line;
		BufferedReader in = null;

		try {
			in = new BufferedReader(new FileReader(new File(filesDir, fileName)));
			while ((line = in.readLine()) != null) {
				stringBuilder.append(line);
			}
			in.close();

		} catch (FileNotFoundException e) {
			Log.e("IO_read", "file not found: "+e.toString());
			return null;
		} catch (IOException e) {
			Log.e("IO_read", "io exception: "+e.toString());
			return null;
		}

		return stringBuilder.toString();
	}


	/**
	 * Append to update log new info.
	 * @param updatelog - the Update Log file
	 * @param key - the key that was updated.
	 * @param version - the version the key file was updated to.
	 * @return true if succeed and false if failed.
	 */
	public static boolean addToConfLog(String updatelog, String key, int version) {
		try {
			FileWriter out = new FileWriter(new File(filesDir,	updatelog), true);
			out.write(key+":"+version+"\n");
			out.close();
		} catch (IOException e) {
			Log.e("IO_addToConfLog", "io exception: "+e.toString());
			return false;
		}
	
		return true;
	}
}